<script setup lang="ts">
import { ref, watch, nextTick, onMounted, onBeforeUnmount } from 'vue'
import { Field, Button, Icon, showToast } from 'vant'

defineProps({
  loading: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['send', 'stop', 'filesUploaded'])

const inputText = ref('')
const showModelSelector = ref(false)
const selectedModel = ref('GLM-Z1-Air')
const uploadedFiles = ref<any[]>([])
const uploadingFiles = ref<boolean[]>([])
const isDragOver = ref(false)
const dragOverlay = ref(false)

const models = [
  { 
    name: 'GLM-Z1-Air', 
    label: 'GLM-Z1-Air', 
    description: '智谱AI最新模型，响应快速，适合日常对话分析'
  },
  { 
    name: 'deepseek-r1:14b', 
    label: 'DeepSeek-R1-14B', 
    description: '深度思考模型，逻辑推理能力强，适合复杂分析'
  }
]

const handleSend = () => {
  if (!inputText.value.trim()) return
  
  const fileContents = uploadedFiles.value.map(file => file.parsedContent).filter(Boolean)
  const fileNames = uploadedFiles.value.map(file => file.name)
  
  emit('send', {
    text: inputText.value,
    model: selectedModel.value === 'GLM-Z1-Air' ? undefined : selectedModel.value,
    files: fileContents,
    fileNames: fileNames
  })
  
  inputText.value = ''
  uploadedFiles.value = []
  uploadingFiles.value = []
}

const handleStopStream = () => {
  emit('stop')
}

const adjustTextareaHeight = (element: HTMLTextAreaElement) => {
  element.style.height = 'auto'
  const lineHeight = 24
  const maxHeight = lineHeight * 6
  const newHeight = Math.min(element.scrollHeight, maxHeight)
  element.style.height = `${newHeight}px`
}

const handleTextareaInput = (event: Event) => {
  const textarea = event.target as HTMLTextAreaElement
  adjustTextareaHeight(textarea)
}

const selectModel = (model: string) => {
  selectedModel.value = model
  showModelSelector.value = false
}

const uploadFile = async (file: any) => {
  if (uploadedFiles.value.length >= 5) {
    showToast('最多只能上传5个文件')
    return
  }
  
  const index = uploadedFiles.value.length
  uploadedFiles.value.push({
    name: file.name,
    size: file.size,
    status: 'uploading',
    parsedContent: ''
  })
  uploadingFiles.value.push(true)
  
  try {
    const formData = new FormData()
    formData.append('file', file)
    
    const response = await fetch(`${import.meta.env.VITE_BASE_URL}/api/tools/tika/file`, {
      method: 'POST',
      body: formData
    })
    
    if (!response.ok) {
      throw new Error(`上传失败: ${response.status}`)
    }
    
    const result = await response.text()
    uploadedFiles.value[index].parsedContent = result
    uploadedFiles.value[index].status = 'success'
    uploadingFiles.value[index] = false
    
  } catch (error) {
    console.error('文件上传失败:', error)
    uploadedFiles.value[index].status = 'failed'
    uploadingFiles.value[index] = false
    showToast('文件上传失败')
  }
}

const removeFile = (index: number) => {
  uploadedFiles.value.splice(index, 1)
  uploadingFiles.value.splice(index, 1)
}

const handleFileSelect = (event: Event) => {
  const target = event.target as HTMLInputElement
  const files = Array.from(target.files || [])
  files.forEach(uploadFile)
  target.value = ''
}

const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
  if (!isDragOver.value) {
    isDragOver.value = true
    dragOverlay.value = true
  }
}

const handleDragLeave = (event: DragEvent) => {
  event.preventDefault()
  if (!event.relatedTarget || !document.body.contains(event.relatedTarget as Node)) {
    isDragOver.value = false
    dragOverlay.value = false
  }
}

const handleDrop = (event: DragEvent) => {
  event.preventDefault()
  isDragOver.value = false
  dragOverlay.value = false
  
  const files = Array.from(event.dataTransfer?.files || [])
  files.forEach(uploadFile)
}

const triggerFileInput = () => {
  const fileInput = document.getElementById('file-input') as HTMLInputElement
  fileInput?.click()
}

onMounted(() => {
  document.addEventListener('dragover', handleDragOver)
  document.addEventListener('dragleave', handleDragLeave)
  document.addEventListener('drop', handleDrop)
})

onBeforeUnmount(() => {
  document.removeEventListener('dragover', handleDragOver)
  document.removeEventListener('dragleave', handleDragLeave)
  document.removeEventListener('drop', handleDrop)
})

watch(inputText, () => {
  nextTick(() => {
    const textareaElement = document.querySelector('.chat-textarea textarea') as HTMLTextAreaElement
    if (textareaElement) {
      adjustTextareaHeight(textareaElement)
    }
  })
})
</script>

<template>
  <div class="input-area">
    <!-- 文件上传栏 -->
    <div v-if="uploadedFiles.length > 0" class="file-upload-bar">
      <div class="file-list">
        <div 
          v-for="(file, index) in uploadedFiles" 
          :key="index"
          class="file-item"
        >
          <div class="file-icon">
            <Icon 
              v-if="file.status === 'uploading'" 
              name="loading" 
              size="14" 
              class="loading-icon"
            />
            <Icon 
              v-else-if="file.status === 'success'" 
              name="passed" 
              size="14" 
              color="#07c160"
            />
            <Icon 
              v-else 
              name="cross" 
              size="14" 
              color="#ee0a24"
            />
          </div>
          <span class="file-name">{{ file.name }}</span>
          <Icon 
            name="close" 
            size="12" 
            class="remove-icon"
            @click="removeFile(index)"
          />
        </div>
      </div>
    </div>

    <div class="input-controls">
      <!-- 模型选择按钮 -->
      <div class="model-selector">
        <button 
          class="model-button" 
          @click="showModelSelector = !showModelSelector"
        >
          <Icon name="setting-o" size="16" />
          <span>{{ selectedModel }}</span>
          <Icon name="arrow-up" size="12" :class="{ rotated: !showModelSelector }" />
        </button>
        
        <!-- 上拉菜单 -->
        <div v-if="showModelSelector" class="model-menu">
          <div 
            v-for="model in models" 
            :key="model.name"
            class="model-option"
            :class="{ active: selectedModel === model.name }"
            @click="selectModel(model.name)"
          >
            <div class="model-info">
              <div class="model-name">{{ model.label }}</div>
              <div class="model-desc">{{ model.description }}</div>
            </div>
            <Icon v-if="selectedModel === model.name" name="passed" size="16" color="#4080ff" />
          </div>
        </div>
      </div>

      <Field
        v-model="inputText"
        type="textarea"
        rows="1"
        autosize
        class="chat-textarea"
        placeholder="请输入您的问题"
        :disabled="disabled || loading"
        @input="handleTextareaInput"
        @keyup.enter.prevent="handleSend"
      >
        <template #button>
          <!-- 文件上传按钮 -->
          <Button 
            class="action-button upload-button" 
            size="small"
            @click="triggerFileInput"
          >
            <Icon name="link-o" size="18" />
            <span>上传文件</span>
          </Button>
          
          <!-- 发送/停止按钮 -->
          <Button 
            v-if="!loading"
            class="action-button send-button" 
            size="small" 
            :disabled="!inputText.trim() || disabled" 
            @click="handleSend"
          >
            <Icon name="guide-o" size="18" />
            <span>发送</span>
          </Button>
          <Button 
            v-else
            class="action-button stop-button" 
            size="small" 
            @click="handleStopStream"
          >
            <Icon name="close" size="18" />
            <span>停止</span>
          </Button>
        </template>
      </Field>
    </div>

    <!-- 隐藏的文件输入框 -->
    <input 
      id="file-input"
      type="file" 
      multiple
      accept=".pdf,.doc,.docx,.xlsx,.ppt,.pptx,.csv,.txt,.jpg,.jpeg,.png,.gif"
      style="display: none"
      @change="handleFileSelect"
    />

    <!-- 拖拽上传蒙版 -->
    <div v-if="dragOverlay" class="drag-overlay">
      <div class="drag-content">
        <Icon name="plus" size="48" color="#1989fa" />
        <h3>文件拖动到此处即可上传</h3>
        <p>支持的文件格式：PDF、Word 文档（DOC、DOCX）、Excel表格(XLSX）、PPT（PPT、PPTX）、图片、CSV、各类纯文本格式等。</p>
        <p>最高支持同时上传5个文件</p>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.input-area {
  padding: 12px 16px;
  background-color: white;
  border-top: 1px solid #eee;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 10;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  
  .file-upload-bar {
    margin-bottom: 12px;
    padding: 12px;
    background-color: #f8f9fa;
    border-radius: 12px;
    border: 1px solid #e8e8e8;
    
    .file-list {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      
      .file-item {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 6px 12px;
        background-color: white;
        border-radius: 20px;
        border: 1px solid #ddd;
        font-size: 12px;
        max-width: 200px;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        
        .file-icon {
          display: flex;
          align-items: center;
          
          .loading-icon {
            animation: rotate 1s linear infinite;
          }
        }
        
        .file-name {
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          color: #333;
          font-weight: 500;
        }
        
        .remove-icon {
          cursor: pointer;
          color: #999;
          transition: color 0.2s;
          
          &:hover {
            color: #ee0a24;
          }
        }
      }
    }
  }
  
  .input-controls {
    display: flex;
    gap: 8px;
    align-items: center;
    
    .model-selector {
      position: relative;
      
      .model-button {
        display: flex;
        align-items: center;
        gap: 6px;
        padding: 8px 12px;
        height: 40px;
        background-color: #f8f9fa;
        color: #606266;
        border: 1px solid #dcdfe6;
        border-radius: 20px;
        font-size: 14px;
        min-width: fit-content;
        white-space: nowrap;
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:hover {
          background-color: #ecf5ff;
          border-color: #b3d8ff;
          color: #409eff;
          // transform: translateY(-1px);
          box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
        }
        
        &:active {
          transform: translateY(0);
          box-shadow: 0 1px 3px rgba(64, 158, 255, 0.3);
        }
        
        .rotated {
          transform: rotate(180deg);
          transition: transform 0.3s ease;
        }
      }
      
      .model-menu {
        position: absolute;
        bottom: 100%;
        left: 0;
        right: auto;
        width: 310px;
        margin-bottom: 8px;
        background: white;
        border-radius: 12px;
        box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
        border: 1px solid #e4e7ed;
        overflow: hidden;
        animation: slideUp 0.3s ease;
        z-index: 100;
        
        .model-option {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 12px 16px;
          cursor: pointer;
          transition: all 0.2s ease;
          border-bottom: 1px solid #f0f0f0;
          
          &:last-child {
            border-bottom: none;
          }
          
          &:hover {
            background-color: #f5f7fa;
          }
          
          &.active {
            background-color: #ecf5ff;
            color: #409eff;
          }
          
          .model-info {
            flex: 1;
            
            .model-name {
              font-size: 14px;
              font-weight: 500;
              margin-bottom: 2px;
            }
            
            .model-desc {
              font-size: 12px;
              color: #909399;
              line-height: 1.4;
            }
          }
        }
      }
    }
    
    .chat-textarea {
      flex: 1;
      background-color: #f8f9fa;
      border-radius: 20px;
      
      :deep(.van-field__body) {
        padding-right: 8px;
      }
      
      :deep(.van-field__control) {
        min-height: 24px;
        max-height: 144px;
        line-height: 24px;
        padding: 8px 0;
        overflow-y: auto;
        resize: none;
        font-size: 15px;
      }
      
      :deep(.van-field__button) {
        align-self: center;
        display: flex;
        gap: 8px;
      }
    }
  }
  
  .upload-button {
    background-color: #f8f9fa;
    color: #606266;
    border: 1px solid #dcdfe6;
    
    &:hover {
      background-color: #ecf5ff;
      border-color: #b3d8ff;
      color: #409eff;
      // transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
    }
    
    &:active {
      transform: translateY(0);
      box-shadow: 0 1px 3px rgba(64, 158, 255, 0.3);
    }
  }
  
  .action-button {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
    padding: 8px 16px;
    border-radius: 20px;
    font-weight: 500;
    font-size: 14px;
    transition: all 0.3s ease;
    
    &.send-button {
      background-color: #4080ff;
      color: white;
      
      &:active {
        background-color: #3070ee;
      }
      
      &[disabled] {
        background-color: #a7c0ff;
        opacity: 0.8;
      }
    }
    
    &.stop-button {
      background-color: #ff4d4f;
      color: white;
      
      &:active {
        background-color: #f5222d;
      }
    }
  }
  
  .drag-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(25, 137, 250, 0.1);
    backdrop-filter: blur(4px);
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: center;
    animation: fadeIn 0.2s ease;
    
    .drag-content {
      text-align: center;
      padding: 40px;
      background-color: white;
      border-radius: 16px;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
      border: 2px dashed #1989fa;
      max-width: 400px;
      
      h3 {
        margin: 16px 0 8px 0;
        color: #1989fa;
        font-size: 18px;
        font-weight: 500;
      }
      
      p {
        margin: 8px 0;
        color: #666;
        font-size: 14px;
        line-height: 1.4;
        
        &:last-child {
          font-weight: 500;
          color: #1989fa;
        }
      }
    }
  }
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@keyframes fadeIn {
  from { opacity: 0; transform: scale(0.95); }
  to { opacity: 1; transform: scale(1); }
}

@keyframes slideUp {
  from { 
    opacity: 0; 
    transform: translateY(10px); 
  }
  to { 
    opacity: 1; 
    transform: translateY(0); 
  }
}
</style>